//
//  ImageSavedViewController.m
//  0.3camera
//
//  Created by 茶 on 2023/11/23.
//

#import "SavedViewController.h"
#import "CASavedCollectionViewCell.h"
#import "CASavedModel.h"
#import "DetailViewController.h"

@interface SavedViewController () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, assign) BOOL isEdit;

@end

@implementation SavedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _isEdit = NO;
    [self initInterface];
    [self initDataSourceWithEdit:NO];
}

- (void)initInterface {
    self.view.clipsToBounds = YES;
    self.view.backgroundColor = UIColor.whiteColor;
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editEvent)];
    [rightItem setTitleTextAttributes:@{NSFontAttributeName:CAFontScaleRegular(18)} forState:UIControlStateNormal];
    rightItem.tintColor = HexColor(@"#29282A");
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self.view addSubview:self.collectionView];
}

- (void)initDataSourceWithEdit:(BOOL)edit {
    NSError *error = nil;

    NSString * path = [NSString stringWithFormat:@"%@/image", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject];
    NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
    if (!error) {
        for (NSString *imgPath in files) {
            CASavedModel *model = [CASavedModel new];
            model.imgPath = [path stringByAppendingFormat:@"/%@", imgPath];
            model.isSelected = NO;
            model.canEdit = edit;
            [self.dataSource addObject:model];
        }
    }
    [self.collectionView reloadData];

    self.navigationItem.title = [NSString stringWithFormat:@"%ld张图片", self.dataSource.count];
}

- (void)editEvent {
    _isEdit = YES;
    for (CASavedModel *model in self.dataSource) {
        model.canEdit = YES;
        model.isSelected = NO;
    }
    [self.collectionView reloadData];
    UIBarButtonItem *delItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"Saved_Nav_1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(deleteEvent)];
    UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelEvent)];
    [cancelItem setTitleTextAttributes:@{NSFontAttributeName:CAFontScaleRegular(18)} forState:UIControlStateNormal];
    cancelItem.tintColor = HexColor(@"#29282A");
    self.navigationItem.rightBarButtonItems = @[delItem, cancelItem];
}

- (void)deleteEvent {
    CAWeakify(self);
    [LEEAlert alert].config
    .LeeTitle(@"提示")         // 添加一个标题 (默认样式)
    .LeeContent(@"确实删除选中图片？")        // 添加一个标题 (默认样式)
    .LeeCancelAction(@"取消", ^{        //添加一个默认类型的Action (默认样式 字体颜色为蓝色)
    })
    .LeeAction(@"确定", ^{    // 添加一个取消类型的Action (默认样式 alert中为粗体 actionsheet中为最下方独立)
        CAStrongify(self);
        for (CASavedModel *model in self.dataSource) {
            if (model.isSelected) {
                [[NSFileManager defaultManager] removeItemAtPath:model.imgPath error:nil];
            }
        }
        [self.dataSource removeAllObjects];
        [self initDataSourceWithEdit:YES];
    })
    .LeeShow();
}

- (void)cancelEvent {
    _isEdit = NO;
    for (CASavedModel *model in self.dataSource) {
        model.isSelected = NO;
        model.canEdit = NO;
    }
    [self.collectionView reloadData];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editEvent)];
    rightItem.tintColor = HexColor(@"#29282A");
    [rightItem setTitleTextAttributes:@{NSFontAttributeName:CAFontScaleRegular(18)} forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItems = @[rightItem];
}

- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    CASavedCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kImageSavedIdentifier forIndexPath:indexPath];
    cell.model = self.dataSource[indexPath.row];
    return cell;
}

- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    CASavedModel *model = self.dataSource[indexPath.row];
    if (!model.canEdit) {
        CAWeakify(self);
        DetailViewController *detailVC = [DetailViewController new];
        detailVC.dataSource = self.dataSource;
        detailVC.index = indexPath.row;
        detailVC.deleteBlock = ^{
            CAStrongify(self);
            [self.dataSource removeAllObjects];
            [self initDataSourceWithEdit:NO];
        };
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat width = (self.view.width - CARatioWidth(40)) / 3;
        layout.itemSize = CGSizeMake(width, width);
        layout.sectionInset = UIEdgeInsetsMake(CARatioWidth(10), CARatioWidth(10), CARatioWidth(10), CARatioWidth(10));
        layout.minimumLineSpacing = CARatioWidth(10);
        layout.minimumInteritemSpacing = CARatioWidth(10);
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.frame = self.view.frame;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = UIColor.clearColor;
        _collectionView.allowsMultipleSelection = YES;
        [_collectionView registerClass:[CASavedCollectionViewCell class] forCellWithReuseIdentifier:kImageSavedIdentifier];

    }
    return _collectionView;
}

- (NSMutableArray *)dataSource {
    if (_dataSource) return _dataSource;
    _dataSource = [NSMutableArray array];
    return _dataSource;
}


@end
